package com.itheima.service;

import com.itheima.annotation.RedisCache;
import com.itheima.annotation.RedisCache2;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.utils.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author itheima
 * @since 2021-10-25
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String login(String phone, String password) {
        // 密码是先进行md5哈希后，再写入数据库，不能直接写入明文密码
        String passwordWithMd5 = HashUtils.getMD5String("itheima" + password);

        List<User> byPhoneAndPassword = userDao.getByPhoneAndPassword(phone, passwordWithMd5);
        if (Objects.isNull(byPhoneAndPassword) || byPhoneAndPassword.size() <= 0) {
            return "账号或密码错误";
        }

        // 生成token
        String token = HashUtils.getMD5String(phone);
        redisTemplate.opsForValue().set("user:token:" + token, phone, 1, TimeUnit.HOURS);
        return token;
    }

    @Override
    public Boolean checkToken(String token) {
        Object o = redisTemplate.opsForValue().get("user:token:" + token);
        return Objects.nonNull(o);
    }

    @Override
    @RedisCache("userService#getAll")
    @RedisCache2("123123")
    public List<User> getAll() {
        return userDao.getAll();
    }
}
